<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>莫得乐色</title>
  <link href="https://cdn.bootcss.com/foundation/6.6.1/css/foundation.min.css" rel="stylesheet">
</head>
<body>
  <div id="gbl-alert"></div>
  <div id="page-close"></div>
  <div id="page-cover"></div>
  <div id="pages"></div>
  <div id="main" class="full-container">
    <div class="grid-x" style="padding:0.8rem;line-height: 2.5rem;background:#ecebef;">
      <div class="cell medium-1 large-2 hide-for-small-only"></div>
      <div class="cell small-12 medium-10 large-8">
        <ul class="menu">
          <li><a href="javascript:_gbl.loadPage('goods');">商品列表</a></li>
          <li><a href="javascript:_gbl.loadPage('newgoods');">上传商品</a></li>
        </ul>
      </div>
      <div class="cell medium-1 large-2 hide-for-small-only"></div>
    </div>

    <div style="margin-top:1.2rem;padding:0.5rem;margin-bottom:1.5rem;">
      <form onsubmit="return false;">
        <div class="grid-x">
          <div class="cell small-2 medium-2 large-2"></div>
          <div class="cell small-5 medium-3 large-1" style="padding-right:0.2rem;">
            <label>年</label>
            <select id="order-year" onchange="_gbl.alertMsg('获取中···')">
            </select>
          </div>
          <div class="cell small-5 medium-3 large-1">
            <label>月</label>
            <select id="order-month" onchange="_gbl.alertMsg('获取中···')">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
              <option value="11">11</option>
              <option value="12">12</option>
            </select>
          </div>
        </div>
      </form>
    </div>

    <div class="grid-x">
      <div class="cell medium-1 large-2 hide-for-small-only"></div>
      <div class="cell small-12 medium-10 large-8">
        <div id="order-list"></div>
      </div>
      <div class="cell medium-1 large-2 hide-for-small-only"></div>
    </div>

  </div>

  <script>

    var yeardom = document.getElementById('order-year');
    var monthdom = document.getElementById('order-month');

    (function (){
      var tm = new Date();
      let year = tm.getFullYear();
      let html = '';
      for (let i=year; i>2019; i--) {
        html += `<option value="${i}">${i}</option>`;
      }
      yeardom.innerHTML = html;
    })();

    (function (){
      var tm = new Date();
      var month = tm.getMonth() + 1;
      for (let i=0; i < monthdom.options.length; i++) {
        if (monthdom.options[i].value == month) {
          monthdom.options[i].selected = true;
          break;
        }
      }
    })();
    
    var _gbl = new function () {

      this.url = location.href;
      this.query = {};

      this.parseUrl = function () {
        if (this.url.indexOf('?') < 0) {
          return ;
        }
        var qs = this.url.split('?')[1];
        var args = qs.split('&');
        let tmp = [];
        for (let i=0; i<args.length; i++) {
          tmp = args[i].split('=');
          if (tmp.length < 2) {
            tmp.push('');
          }
          this.query[tmp[0]] = decodeURIComponent(tmp[1]);
        }
      };

      this.alert = function (info) {
        var adom = document.getElementById('gbl-alert');
        if (adom === null) {
          return ;
        }
        adom.style.cssText = 'z-index:99;position:fixed;width:45%;left:27.5%;min-height:10%;background:#fafaff;line-height:2.2rem;top:5%;padding:0.5rem;';
        adom.innerHTML = `<div>
          <p style="text-align:right;"><a href="javascript:_gbl.unalert();">X</a></p>
          <div style="text-align:center;">${info}</div>
        </div>`;
      };

      this.unalert = function () {
        var adom = document.getElementById('gbl-alert');
        if (adom === null) {
          return ;
        }
        adom.innerHTML = '';
        adom.style.cssText = '';
      };

      this.getToken = function () {
        return localStorage.getItem('modelese-token');
      };

      this.setToken = function (token) {
        localStorage.setItem('modelese-token', token);
      };

      this.delToken = function () {
        localStorage.removeItem('modelese-token');
      };

      this.renderList = function (adom, data, callback) {
        if (typeof adom === 'string') {
          adom = document.getElementById(adom);
        }
        if (!adom) {
          return ;
        }
        var html = '';
        for(let i=0; i<data.length; i++) {
          html += callback(data[i]);
        }
        adom.innerHTML = html;
      };

      this.alertError = function (errinfo) {
        this.alert(`<p style="color:#561234;">${errinfo}</p>`);
        var self = this;
        setTimeout(() => {
          self.unalert();
        }, 3500);
      };

      this.alertMsg = function (info) {
        this.alert(`<p style="color:#696969;font-size:120%;">${info}</p>`);
        var self = this;
        setTimeout(() => {
          self.unalert();
        }, 1500);
      };

      //this.host = 'https://wx.modelese.cn';
      this.host = '';

      this.apicall = async function (path, options = {}) {
        var self = this;
        var q = '?';
        if (path.indexOf('?') > 0) {
          q = '&';
        }
        path += `${q}token=${this.getToken()}`;
        if (path[0] !== '/') {
          path = `/${path}`;
        }
        return fetch(`${this.host}${path}`, options).then(res => {
          if (res.ok) {
            return res.json();
          } else {
            throw new Error(`${res.status}: ${res.statusText}`);
          }
        }, err => {
          throw err;
        }).catch(err => {
          self.alertError(err.message);
        });
      };

      this.pagedom = null;
      this.initPage = function (id) {
        this.pagedom = document.getElementById(id);
      };

      this.clearPage = function () {
        if (this.pagedom) {
          this.pagedom.innerHTML = '';
        }
      };

      this.pages = {};
      this.curPage = null;

      this.loadPage = function (name) {
        if (this.pagedom === null) {
          return ;
        }
        if (this.pages[name] === undefined) {
          this.alertError('页面没有发现');
          return ;
        }
        var page = this.pages[name];
        if (page === null || typeof page !== 'object') {
          this.alertError('错误的页面对象');
          return ;
        }

        if (this.curPage !== null) {
          if (this.curPage.onunload && typeof this.curPage.onunload === 'function') {
            this.curPage.onunload();
          }
        }

        this.curPage = page;

        if (page.init && typeof page.init === 'function' && !page.initFlag) {
          page.initFlag = true;
          page.init();
        }

        if (page.view && typeof page.view === 'function') {
          this.showPage();
          let html = page.view(this);
          this.pagedom.innerHTML = html;
        }

        if (page.onload && typeof page.onload === 'function') {
          page.onload(this);
        }

      };

      this.showPage = function () {
        if (this.pagedom) {
          this.pagedom.style.cssText = 'z-index:10;position:fixed;width:90%;height:90%;background:#ffffff;left:5%;top:0.1%;';
        }
        let closedom = document.getElementById('page-close');
        if (closedom) {
          closedom.style.cssText = 'z-index:10;position:fixed;width:3rem;height:3rem;line-height:3rem;text-align:center;right:4%;bottom:2.5%;border-radius:1.5rem;background:#df6721;font-size:120%;';
          closedom.innerHTML = '<a href="javascript:_gbl.hidePage();">X</a>';
        }
        let pgcover = document.getElementById('page-cover');
        if (pgcover) {
          pgcover.style.cssText = 'z-index:1;position:fixed;width:100%;height:100%;background:rgba(12,12,12,0.5);';
        }
      };

      this.hidePage = function () {
        this.pagedom.style.cssText = 'height:0px;display:none;';
        let closedom = document.getElementById('page-close');
        if (closedom) {
          closedom.style.cssText = '';
          closedom.innerHTML = '';
        }
        let pgcover = document.getElementById('page-cover');
        if (pgcover) {
          pgcover.style.cssText = '';
        }
      };

      this.resizePage = function () {
        if (this.pagedom) {
          let dh = document.documentElement.clientHeight;
          this.pagedom.style.minHeight = `${dh * 0.9}px`;
        }
      }

    };

    var goodspg = new function () {

      this.init = function () {

      };

      this.view = function (gbl) {
        return `<div id="goods-list" class="grid-x"></div>`;
      };

      this.glist = {};

      this.renderGoods = function(a) {
        return `<p>${a.goods_name}</p>
          <p>${a.points}</p>
          <p>${a.storage}</p>
          <div>
            <a href="javascript:goodspg.edit('${a.id}');" style="color:#565656;">
            编辑</a>&nbsp;&nbsp;
            <span ondblclick="goodspg.deleteGoods('${a.id}');" style="color:#df5619;" title="双击删除">删除</span>
          </div>`;
      };

      this.showList = function (gl) {
        _gbl.renderList(document.getElementById('goods-list'), gl, a => {
            let imghtml = '';
            let images = a.goods_image.split(',').filter(p => p.length > 0);
            for(let i=0; i<images.length; i++) {
              imghtml += `<img src="/common/image/${images[i]}" style="height:4rem;width:auto;margin-right:0.25rem;">`;
            }
            return `<div class="cell small-12 medium-6 large-4" style="padding:0.5rem;">
                <div style="background:#f1f2f3;">
                  <div id="goods-${a.id}">
                    ${goodspg.renderGoods(a)}
                  </div>
                  <div style="height:4.2rem;overflow-x:auto;">${imghtml}</div>
                </div>
                
              </div>`;
          });
      };

      this.goodsList = function () {

        _gbl.apicall('/admin/goods').then(d => {
          for (let i=0; i<d.data.length; i++) {
            this.glist[d.data[i].id] = d.data[i];
          }
          goodspg.showList(d.data);
        });
      };

      this.onload = function (gbl) {
        this.goodsList();
      };

      this.edit = function (id) {
        let gm = document.getElementById('goods-'+id);
        if (!gm) {
          return ;
        }
        let g = this.glist[id];
        if (!g) {
          return ;
        }
        gm.innerHTML = `
            <label>名称</label>
            <input type="text" value="${g.goods_name}" id="goods-name-${id}">
            <label>积分</label>
            <input type="text" value="${g.points}" id="goods-points-${id}">
            <label>库存</label>
            <input type="text" value="${g.storage}" id="goods-storage-${id}">
          <button onclick="goodspg.update('${id}', this);" class="button tiny success">确定</button>&nbsp;&nbsp;
          <button onclick="goodspg.cancel('${id}');" class="button tiny secondary">取消</button>
        `;
      };

      this.deleteGoods = function (id) {
        _gbl.apicall('/admin/goods/'+id, {
          method : 'DELETE',
        }).then(d => {
          if (d.status == 'OK') {
            delete goodspg.glist[id];
            let gs = [];
            for(let k in goodspg.glist) {
              gs.push(goodspg.glist[k]);
              goodspg.showList(gs);
            }
          } else {
            _gbl.alertError(d.errmsg);
          }
        })
      };

      this.cancel = function (id) {
        let html = this.renderGoods(goodspg.glist[id]);
        let gm = document.getElementById('goods-'+id);
        gm.innerHTML = html;
      };

      this.update = function (id, btn) {
        let g = {
          points : document.getElementById('goods-points-'+id).value.trim(),
          storage : document.getElementById('goods-storage-'+id).value.trim(),
          goods_name : document.getElementById('goods-name-'+id).value.trim(),
        };
        if (!g.goods_name || !g.points) {
          _gbl.alertError('goods_name 和 points不能为空');
          return ;
        }
        btn.disabled = true;
        _gbl.apicall('/admin/goods/'+id, {
          method : 'PUT',
          headers : {
            'content-type' : 'text/plain'
          },
          body : JSON.stringify(g)
        }).then(d => {
          btn.disabled = false;
          if (d.status == 'OK') {
            let a = goodspg.glist[id];
            a.points = g.points;
            a.storage = g.storage;
            a.goods_name = g.goods_name;
            let html = goodspg.renderGoods(a);
            document.getElementById('goods-'+id).innerHTML = html;
          } else {
            _gbl.alertError(d.errmsg);
          }
        });
      }

    };

    var newgpg = new function () {

      this.init = function () {
        if (!sessionStorage.getItem('new-goods-init')) {
          sessionStorage.setItem('new-goods-init', '1');
          let g = {
            goods_name : '',
            points : 0,
            storage : 0,
            goods_image : []
          };
          sessionStorage.setItem('new-goods-cache', JSON.stringify(g));
        }
      };

      this.cacheNewGoods = function (t, field) {
        let g = JSON.parse(sessionStorage.getItem('new-goods-cache'));
        switch (field) {
          case 'name':
            g.goods_name = t.value; break;
          case 'storage':
            g.storage = t.value; break;
          case 'points':
            g.points = t.value; break;
          default:;
        }
        sessionStorage.setItem('new-goods-cache', JSON.stringify(g));
      }

      this.view = function (gbl) {
        return `<div class="grid-x" style="margin-top:0.8rem;">
          <div class="cell medium-2 large-3"></div>
          <div class="cell small-12 medium-8 large-6">
            <h3>上传商品</h3>
            <form onsubmit="return false;">
              <label>商品名称</label>
              <input type="text" id="new-goods-name" value="" placeholder="商品名称" onchange="newgpg.cacheNewGoods(this, 'name');" required>
              
              <label>需要积分</label>
              <input type="number" id="new-goods-points" value="100" placeholder="需要积分" onchange="newgpg.cacheNewGoods(this, 'points');" required>
              
              <label>库存</label>
              <input type="number" id="new-goods-storage" value="1" placeholder="库存" onchange="newgpg.cacheNewGoods(this, 'storage');" required>

              <label>上传图片</label>
              <input type="file" id="new-goods-image" value="" onchange="newgpg.uploadGoodsImage(this);"><br>
              <div style="text-align:right;">
              <input type="submit" class="button small primary" value="提交" onclick="newgpg.submitGoods(this);"></div>
            </form>
            <div id="goods-image-list" style="width:100%;"></div>
          </div>
          <div class="cell medium-2 large-3"></div>
          </div>`;
      };

      this.uploadGoodsImage = function (t) {
        var file = t.files[0];
        var postform = new FormData();
        postform.append('image', file);
        _gbl.apicall('/admin/image', {
          method : 'POST',
          body : postform
        }).then(d => {
          if (d.status == 'OK') {
            let g = JSON.parse(sessionStorage.getItem('new-goods-cache'));
            g.goods_image.push(d.data);
            sessionStorage.setItem('new-goods-cache', JSON.stringify(g));
            newgpg.showGoodsImage(g.goods_image);
            t.value = '';
          } else {
            _gbl.alertError(d.errmsg);
          }
        });
      };

      this.submitGoods = function (tbtn) {
        let g = JSON.parse(sessionStorage.getItem('new-goods-cache'));
        if (g.goods_name.trim()  == '') {
          _gbl.alertError('名称不能为空');
          return ;
        }
        if (g.points <= 0) {
          _gbl.alertError('积分需要大于0');
          return ;
        }
        if (g.storage < 0) {
          _gbl.alertError ('库存不能小于0');
          return ;
        }
        tbtn.disabled = true;
        g.goods_image = g.goods_image.join(',');
        _gbl.apicall('/admin/goods', {
          method : 'POST',
          body : JSON.stringify(g),
          headers : {
            'content-type' : 'text/plain'
          }
        }).then(d => {
          if (d.status == 'OK') {
            document.getElementById('new-goods-name').value = '';
            document.getElementById('new-goods-points').value = '';
            document.getElementById('new-goods-storage').value = '';
            document.getElementById('goods-image-list').innerHTML = '';
            g.goods_name = '';
            g.points = 0;
            g.storage = 0;
            g.goods_image = [];
            sessionStorage.setItem('new-goods-cache', JSON.stringify(g));
          } else {
            _gbl.alertError(d.errmsg);
          }
        }).finally(() => {
          tbtn.disabled = false;
        });
      };

      this.showGoodsImage = function (images) {
        var html = '';
        for (let i=0; i<images.length; i++) {
          html += `
            <img src="/common/image/${images[i]}" style="height:4.5rem;width:auto;margin-right:0.3rem;" ondblclick="newgpg.deleteImage('${images[i]}');" title="双击删除">`;
        }
        document.getElementById('goods-image-list').innerHTML = html;
      };

      this.deleteImage = function (imgname) {
        _gbl.apicall('/admin/image/'+imgname, {
          method : 'DELETE'
        }).then(d => {
          if (d.status == 'OK') {
            let g = JSON.parse(sessionStorage.getItem('new-goods-cache'));
            for (let i=0;i<g.goods_image.length; i++) {
              if (g.goods_image[i] == imgname) {
                g.goods_image.splice(i,1); break;
              }
            }
            sessionStorage.setItem('new-goods-cache', JSON.stringify(g));
            newgpg.showGoodsImage(g.goods_image);
          } else {
            _gbl.alertError(d.errmsg);
          }
        });
      };


      this.onload = function (gbl) {
        let g = JSON.parse(sessionStorage.getItem('new-goods-cache'));
        document.getElementById('new-goods-name').value = g.goods_name;
        document.getElementById('new-goods-points').value = g.points;
        document.getElementById('new-goods-storage').value = g.storage;
        newgpg.showGoodsImage(g.goods_image);
      };

    };

    var ordpg = new function () {
      this.init = function () {
        if (!sessionStorage.getItem('order-init')) {
          sessionStorage.setItem('order-init', '1');
          /* sessionStorage.setItem('order-page', '1');
          sessionStorage.setItem('order-year', `${(new Date()).getFullYear()}`);
          sessionStorage.setItem('order-status', '0'); */
        }
      };

      this.confirmOrder = function (oid) {
        _gbl.apicall('/admin/order/'+oid, {
          method : 'PUT'
        }).then(d => {
          if (d.status !== 'OK') {
            _gbl.alertError(d.errmsg);
          } else {
            var dm = document.getElementById('order-status-'+oid);
            if (dm) {
              dm.innerHTML = '订单状态：已确认';
            }
          }
        });
      };

      this.orderStatus = {
        'd0' : '未确认',
        'd1' : '已确认',
        'd2' : '用户取消'
      };

      this.orderList = function () {
        var self = this;
        var year = yeardom.options[yeardom.selectedIndex].value;
        var month = monthdom.options[monthdom.selectedIndex].value;

        var querystring = `year=${year}&month=${month}`;

        _gbl.apicall(`/admin/order?${querystring}`).then(d => {
          _gbl.renderList(document.getElementById('order-list'), d.data, (a) => {
            var ostext = ordpg.orderStatus[ `d${a.order_status}` ];
            var ostconfirm = '';
            if (a.order_status == 0) {
              ostconfirm = `<br><button class="button success tiny" ondblclick="ordpg.confirmOrder('${a.id}')">双击确认</button>`;
            }
            return `<div class="grid-x" style="line-height:2rem;padding:0.6rem;margin-top:0.5rem;margin-bottom:0.2rem;background-color:#f2f1f3;">
                <div class="cell small-12 medium-6 large-4">
                  订单号：${a.id}
                </div>
                <div class="cell small-12 medium-6 large-4">
                  用户ID：${a.user_id}
                </div>
                <div class="cell small-12 medium-6 large-4">
                  商品：${a.goods_name} X ${a.number}
                </div>
                <div class="cell small-12 medium-6 large-4">
                  消耗积分：${a.points}
                </div>
                <div class="cell small-12 medium-6 large-4">
                  <strong id="order-status-${a.id}">
                    订单状态：${ostext}
                    ${ostconfirm}
                  </strong>
                </div>
                <div class="cell small-12 medium-6 large-4">
                  ${a.order_time}
                </div>
              </div>`;
          });
        });
      };

      this.view = function (g) {
        this.orderList();
      };

      this.onload = function (g) {
        var self = this;
        setInterval(() => {
          self.orderList();
        }, 1200);
      };

    };

    if (location.href.indexOf('token=') < 0) {
      _gbl.alert('请验证token');
    } else {
      _gbl.parseUrl();
      if (_gbl.query.token) {
        _gbl.setToken(_gbl.query.token);
      }
      _gbl.initPage('pages');
      _gbl.pages.goods = goodspg;
      _gbl.pages.newgoods = newgpg;
      ordpg.init();
      ordpg.view();
      ordpg.onload();
    }

    window.onresize = function () {
      _gbl.resizePage();
    };

  </script>

  <script>

  </script>
</body>
</html>